/**
 * 抵用券广告管理
 */
var queryVoucherAdvertSearch = function() {
	var queryVoucherAdvertFieldSet = new Ext.form.FieldSet({
				id : 'queryVoucherAdvertFieldSet',
				title : '查询条件',
				collapsible : true,// 可折叠
				buttonAlign : 'center',
				keys : [{
							key : 13, // 13代表回车
							fn : queryVoucherAdvert,
							scope : this
						}],
				items : [{
					layout : 'column',
					border : false,
					items : [{
						columnWidth : .25,
						layout : 'form',
						border : false,
						items : [{
									xtype : 'textfield',
									id : 'voucherAdvert_title',
									anchor : '100%',
									fieldLabel : '广告标题',
									name : "advTitle"
								}, {
									xtype : "datetimefield",
									id : "voucherFormStartDate",
									name : "formStartDate",
									fieldLabel : "开始日期",
									width : 175,
									editable : true,
									format : "Y-m-d H:i:s",
									listeners : {
										'select' : function() {
											Ext.getCmp('voucherFormEndDate')
													.setMinValue(this
															.getValue());
										}
									}
								}]
					}, {
						columnWidth : .25,
						layout : 'form',
						border : false,
						items : [{
									xtype : 'dataDictionaryCmb',
									anchor : '100%',
									fieldLabel : '状态',
									hiddenName : "advStatus",
									editable : false,
									autoLoad : false,
									existall : true,
									defaultFirstRow : 1,
									dictionaryType : PmsUtil.adv_status
								}, {
									columnWidth : .25,
									layout : 'form',
									border : false,
									items : [{
										width : 175,
										id : "voucherFormEndDate",
										xtype : "datetimefield",
										name : "formEndDate",
										fieldLabel : "结束日期",
										editable : false,
										listeners : {
											'select' : function() {
												Ext.getCmp('voucherFormStartDate')
														.setMaxValue(this
																.getValue());
											}
										}
									}]
								}]
					}, {
						columnWidth : .25,
						layout : 'form',
						border : false,
						items : [{
									layout : 'column',
									border : false,
									items : [{
										text : '查询',
										xtype : 'button',
										width : 80,
										handler : function() {
											queryVoucherAdvert();
										},
										style : {
											marginLeft : "100px",
											marginRight : "10px"
										}
									}, {
												text : '重置',
												xtype : 'button',
												width : 80,
												handler : function() {
													Ext
															.getCmp('queryVoucherAdvertForm')
															.getForm().reset();
													// 对日期的初始设置
													Ext
															.getCmp('voucherFormStartDate')
															.setMaxValue(new Date());
													Ext.getCmp('voucherFormEndDate')
															.setMinValue("");
												}
											}]
								}]
					}]
				}]
			});
	fieldSetListeners(['queryVoucherAdvertFieldSet', 'queryVoucherAdvertForm',
					'voucherAdvertManagerGrid'], [0.16, 0.84]);

	var queryVoucherAdvertForm = new Ext.form.FormPanel({
				id : 'queryVoucherAdvertForm',
				anchor : '100% 16%',
				frame : true,
				labelAlign : 'right',
				bodyBorder : false,
				items : [queryVoucherAdvertFieldSet]
			});
	return queryVoucherAdvertForm;
};

/**
 * grids
 */

var voucherAdvertManagerGrid = function() {
	var voucherAdvertManagerSm = new Ext.grid.CheckboxSelectionModel();// 创建选择模式对象
	// 定义表的每列（对应表头信息）
	var voucherAdvertManagerCm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(),
			{
				dataIndex : "id",
				header : "广告编号",
				sortable : true,
				width : 60
			}, {
				dataIndex : "advTitle",
				header : "广告标题",
				sortable : true,
				width : 70
			}, {
				dataIndex : "advPicPath",
				header : "广告图片",
				sortable : true,
				width : 100,
				renderer : function(value) {
					return PmsUtil.ShowPicture(value);

				}
			}, {
				dataIndex : "advOrder",
				header : "排序",
				sortable : true,
				width : 60,
				editor : {
					xtype : 'textfield'
				}
			}, {
				dataIndex : "advStatus",
				header : "状态",
				sortable : true,
				width : 60,
				renderer : function(value) {
					if (value == 1) {
						return '<div style="color:red;">'
								+ PmsUtil.AdvStatus(value) + '</div>';
					}
					return PmsUtil.AdvStatus(value);
				}
			}, {
				dataIndex : "startDate",
				header : "开始时间",
				sortable : true,
				width : 130
			}, {
				dataIndex : "endDate",
				header : "结束时间",
				sortable : true,
				width : 130

			}, {
				dataIndex : "createdName",
				header : "创建人",
				sortable : true,
				width : 80
			}, {
				dataIndex : "createdDate",
				header : "创建时间",
				sortable : true,
				width : 130
			}, {
				dataIndex : "updatedName",
				header : "修改人",
				sortable : true,
				width : 80
			}, {
				dataIndex : "updatedDate",
				header : "修改时间",
				sortable : true,
				width : 130
			},  {
				header : "管理",
				width : 100,
				dataIndex : "id",
				sortable : false,
				renderer : function(j, i, g, m, h) {
					var l = g.data.id;
					var advStatus = g.data.advStatus;
					var k = "";
					if (isGranted("vaManager_编辑广告")) {
						if (advStatus == "1") {
							k += '&nbsp;&nbsp;<a href="#" onclick="updateAdvert('
									+ l + ');" >修改</a>';
						}

					}
					if (isGranted("vaManager_禁用广告")) {
						if (advStatus == "1") {
							k += '&nbsp;&nbsp;<a href="#" onclick="updAdvertStatus('
									+ l
									+ ','
									+ "0"
									+ ','
									+ "'禁用'"
									+ ')\" >禁用</a>';
						}

					}
					if (isGranted("vaManager_启用广告")) {
						if (advStatus == "0") {
							k += '&nbsp;&nbsp;<a href="#" onclick="updAdvertStatus('
									+ l
									+ ','
									+ "1"
									+ ','
									+ "'启用'"
									+ ')\" >启用</a>';
						}

					}
					return k;
				}
			}]);

	// 定义分析器
	var advManagerReader = new Ext.data.JsonReader({
				totalProperty : "totalCount",
				root : "list",
				fields : [{
							name : "id"
						}, {
							name : "advTitle"
						}, {
							name : "advPicPath"
						}, {
							name : "advStatus"
						}, {
							name : "advOrder"
						}, {
							name : "startDate"
						}, {
							name : "endDate"
						}, {
							name : "createdName"
						}, {
							name : "createdDate"
						}, {
							name : "updatedName"
						}, {
							name : "updatedDate"
						}]
			});

	// 取数据store
	var adervtViewStore = new Ext.data.Store({
				autoLoad : true,// 要加载数据必须设置为true
				proxy : new Ext.data.HttpProxy({
							url : __ctxPath + "/voucherManager/selectVoucherAdverts"
						}),
				remoteSort : false,
				baseParams : {
					start : 0,
					limit : 25
				},
				listeners : {
					beforeload : {
						fn : function(thiz, options) {
							Ext.apply(thiz.baseParams, Ext
											.getCmp('queryVoucherAdvertForm')
											.getForm().getValues());
						}
					}
				},
				reader : advManagerReader
			});

	// 定义grid的toolbar
	var vaManagerTb = new Ext.Toolbar({
				id : "vaManagerTb",
				height : 25,
				items : []
			});

	vaManagerTb.add(new Ext.scm.Button({
				text : "添加广告",
				iconCls : "btn-add",
				width : 80,
				hsValue : 'vaManager_添加广告',
				pressed : true,
				listeners : {
					"click" : function() {
						addAdvert();
					}
				}
			}));

	vaManagerTb.add(new Ext.scm.Button({
				text : "排序批量修改",
				iconCls : "btn-edit",
				width : 80,
				pressed : true,
				hsValue : "vaManager_批量修改",
				listeners : {
					"click" : function() {
						updAdverts();
					}
				}
			}));
	vaManagerTb.add(new Ext.scm.Button({
				text : "刷 新",
				iconCls : "btn-refresh",
				width : 80,
				hsValue : "vaManager_刷新",
				pressed : true,
				handler : function() {
					queryVoucherAdvert();
				}
			}));
	var voucherAdvertManagerGrid = new Ext.grid.EditorGridPanel({
				id : 'voucherAdvertManagerGrid',
				store : adervtViewStore,
				cm : voucherAdvertManagerCm,
				sm : voucherAdvertManagerSm,
				autoScroll : true,
				clicksToEdit : 1,
				loadMask : true,
				trackMouseOver : true,
				stripeRows : true,
				columnLines : true,
				loadMask : {
					msg : "正在加载数据，请稍侯……"
				},
				viewConfig : {
					emptyText : '没有您想要的数据!'
				},
				anchor : '100% 84%',
				frame : true,
				tbar : vaManagerTb,
				bbar : new PG.PagingBar({
							store : adervtViewStore
						})
			});
	return voucherAdvertManagerGrid;
};

// 查询
function queryVoucherAdvert() {
	PmsUtil.StringTrim("voucherAdvert_title");
	var grid = Ext.getCmp("voucherAdvertManagerGrid");
	var form = Ext.getCmp("queryVoucherAdvertForm");
	if (form.getForm().isValid()) {
		var gridStore = grid.getStore();
		gridStore.baseParams = Ext.apply(gridStore.baseParams, form.getForm()
						.getValues());
		gridStore.load();
	}
}

// 添加广告
function addAdvert() {
	try {
		addOrUpdVoucherAdvert(null, "新增广告").show();
	} catch (Error) {
		Ext.Loader.load([__ctxPath + '/js/voucher/voucherAdvertForm.js'], function() {
			addOrUpdVoucherAdvert(null, "新增广告").show();
				});
	}
}

// 修改广告
function updateAdvert(advertId) {
	try {
		addOrUpdVoucherAdvert(advertId, "编辑广告").show();
	} catch (Error) {
		Ext.Loader.load([__ctxPath + '/js/voucher/voucherAdvertForm.js'], function() {
			addOrUpdVoucherAdvert(advertId, "编辑广告").show();
				});
	}
}

// 修改状态
function updAdvertStatus(advertId, status, message) {
	Ext.Msg.confirm("信息确认", "是否" + message + "该条广告信息?", function(btn) {
				if (btn == "yes") {
					var optionMask = new Ext.LoadMask(Ext.getBody(), {
								msg : "正在处理,请稍后..."
							});
					optionMask.show();
					Ext.Ajax.request({
								url : __ctxPath
										+ "/voucherManager/updateAdvStatusById",
								params : {
									advertId : advertId,
									status : status
								},
								method : "post",
								success : function(response) {
									optionMask.hide();
									var jsonData = Ext.util.JSON
											.decode(response.responseText);
									if (jsonData.success) {
										Ext.MessageBox.show({
													title : "信息提示",
													msg : jsonData.data,
													buttons : Ext.MessageBox.OK,
													icon : Ext.MessageBox.INFO
												});
										queryVoucherAdvert();
									} else {
										Ext.MessageBox.show({
													title : "错误提示",
													msg : jsonData.data,
													buttons : Ext.MessageBox.OK,
													icon : Ext.MessageBox.ERROR
												});
									}
								},
								failure : function(response) {
									optionMask.hide();
									Ext.MessageBox.show({
												title : "操作信息",
												msg : "服务器请求异常,请稍后再试!",
												buttons : Ext.MessageBox.OK,
												icon : Ext.MessageBox.ERROR
											});
								}
							});
				}
			});
}

/**
 * 修改排序
 */
function updAdverts() {
	/*
	 * var saveMask = new Ext.LoadMask(Ext.getBody(), { msg : "请稍候..." });
	 * saveMask.show();
	 */
	// var modiRecords = Ext.getCmp("voucherAdvertManagerGrid").getStore().getRange();
	var modiRecords = Ext.getCmp("voucherAdvertManagerGrid").getStore()
			.getModifiedRecords();
	if (modiRecords.length == 0) {
		
		Ext.MessageBox.show({
					title : '提示',
					msg : '当前没有数据修改',
					buttons : Ext.MessageBox.OK,
					icon : Ext.MessageBox.WARNING
				});
		return;
	};

	var advertsUpdArr = new Array();
	for (var i = 0; i < modiRecords.length; i++) {
		var temrecord = new Ext.data.Record();
		temrecord.set("id", modiRecords[i].data.id);
		temrecord.set("advOrder", modiRecords[i].data.advOrder);
		advertsUpdArr.push(temrecord.data);
	}
	var jsonList = Ext.encode(advertsUpdArr);

	Ext.Msg.confirm("信息确认", "是否批量修改广告排序？", function(btn) {
				if (btn == 'yes') {
					var optionMask = new Ext.LoadMask(Ext.getBody(), {
								msg : "正在处理,请稍后..."
							});
					optionMask.show();
					Ext.Ajax.request({
								url : __ctxPath + "/voucherManager/updateVoucherOrders",
								params : {
									jsonList : Ext.util.Format.htmlDecode(Ext
											.encode(advertsUpdArr)).trim()
								},
								method : "post",
								success : function(response) {
									optionMask.hide();
									var jsonData = Ext.util.JSON
											.decode(response.responseText);
									if (jsonData.success) {
										Ext.MessageBox.show({
													title : "信息提示",
													msg : jsonData.data,
													buttons : Ext.MessageBox.OK,
													icon : Ext.MessageBox.INFO
												});
										queryAdvert();
									} else {
										Ext.MessageBox.show({
													title : "错误提示",
													msg : jsonData.data,
													buttons : Ext.MessageBox.OK,
													icon : Ext.MessageBox.ERROR
												});
									}
								},
								failure : function(response) {
									optionMask.hide();
									Ext.MessageBox.show({
												title : "操作信息",
												msg : "服务器请求异常,请稍后再试!",
												buttons : Ext.MessageBox.OK,
												icon : Ext.MessageBox.ERROR
											});
								}
							});
				}
			});
}

Ext.getCmp("centerTabPanel").getActiveTab().add(queryVoucherAdvertSearch(),
		voucherAdvertManagerGrid());
Ext.getCmp("centerTabPanel").getActiveTab().doLayout();
